local weijin = fk.CreateSkill {
  name = "3s__weijin",
  tags = {Skill.Limited},
}

Fk:loadTranslationTable{
  ["3s__weijin"] = "唯进",
  [":3s__weijin"] = "限定技，一名角色杀死角色后，你可展示所有手牌，若你的手牌和弃牌堆中有游戏中所有的【无懈可击】，其将体力上限减至1，否则你弃置其四张牌。",
  ["#3s__weijin"] = "唯进：选择是否发动技能",
  ["#weijin-choose"] = "请选择弃置 %dest 的 %arg 张牌",
  ["$3s__weijin1"] = "进则生，退则死！",
  ["$3s__weijin2"] = "唯有一战，方得生机！",
}

-- 唯进技能：角色死亡时触发
weijin:addEffect(fk.Death, {
  can_trigger = function(self, event, target, player, data)
    -- 基于FreeKill DeathData结构：data.who死亡角色，data.killer凶手
    return player:hasSkill(weijin.name) and data.killer and data.killer ~= player and data.killer:isAlive()
    and player:usedSkillTimes(weijin.name, Player.HistoryGame) == 0 and not player:isKongcheng()
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local killer = data.killer  -- 凶手，对应DeathData.killer
    -- 展示所有手牌
    player:showCards(player:getCardIds("h"))
    -- 获取所有区域的无懈可击（更高效的实现）
    local allNullifications = table.filter(Fk:getAllCardIds(), function (id)
      return Fk:getCardById(id, true).trueName == "nullification"
    end)
    -- 检查是否包含所有游戏中的无懈可击（优化逻辑）
    local hasAllNullifications = table.every(allNullifications, function (id)
      return table.contains(player:getCardIds("he"), id) or room:getCardArea(id) == Card.DiscardPile
    end)
    if hasAllNullifications then
      -- 效果1：将体力上限减至1（更安全的实现）
      room:changeMaxHp(killer, 1 - killer.maxHp)
    else
      -- 效果2：弃置其四张牌
      local cards = killer:getCardIds("he")
      if #cards > 0 then
        local discardNum = math.min(4, #cards)
        if #cards <= 4 then
          -- 如果牌数≤4，直接弃置所有牌
          killer:throwAllCards("he")
        else
          -- 使用askToChooseCards让技能发动者选择要弃置的牌
          local toDiscard = room:askToChooseCards(player, {
            target = killer,
            flag = "he",
            min = discardNum,
            max = discardNum,
            skill_name = weijin.name,
            prompt = "#weijin-choose::" .. killer.id .. ":" .. discardNum
          })
          if toDiscard and #toDiscard > 0 then
            room:throwCard(toDiscard, weijin.name, killer, player)
          else
            -- 如果取消选择，随机弃置4张牌
            local randomCards = table.random(cards, discardNum)
            room:throwCard(randomCards, weijin.name, killer, player)
          end
        end
      end
    end
  end,
})

return weijin